import type { IScheduleState, IScheduleConflict } from './scheduleStore';
import type { IScheduleTemplate } from '@/types/schedule/scheduleTemplate';
import type { IScheduleInstance } from '@/types/schedule/scheduleInstance';
import { 
  ScheduleTemplateStatusEnum, 
  ScheduleInstanceStatusEnum, 
  DayOfWeekEnum 
} from '@/types/schedule/enums';

/**
 * 课表选择器函数集合
 * @description 提供各种数据查询和计算的选择器函数
 */
export const scheduleSelectors = {
  // 模板选择器
  /** 获取所有模板 */
  getAllTemplates: (state: IScheduleState): IScheduleTemplate[] => state.templates,
  
  /** 获取活跃模板 */
  getActiveTemplates: (state: IScheduleState): IScheduleTemplate[] => 
    state.templates.filter(template => template.status === ScheduleTemplateStatusEnum.ACTIVE),
  
  /** 根据ID获取模板 */
  getTemplateById: (state: IScheduleState, id: string): IScheduleTemplate | undefined => 
    state.templates.find(template => template.id === id),
  
  /** 根据学生ID获取模板 */
  getTemplatesByStudentId: (state: IScheduleState, studentId: string): IScheduleTemplate[] => 
    state.templates.filter(template => template.studentId === studentId),
  
  /** 根据课程ID获取模板 */
  getTemplatesByCourseId: (state: IScheduleState, courseId: string): IScheduleTemplate[] => 
    state.templates.filter(template => template.courseId === courseId),
  
  /** 根据星期获取模板 */
  getTemplatesByDayOfWeek: (state: IScheduleState, dayOfWeek: DayOfWeekEnum): IScheduleTemplate[] => 
    state.templates.filter(template => template.dayOfWeek === dayOfWeek),
  
  /** 获取有剩余次数的模板 */
  getTemplatesWithRemainingCount: (state: IScheduleState): IScheduleTemplate[] => 
    state.templates.filter(template => 
      template.status === ScheduleTemplateStatusEnum.ACTIVE && 
      template.completedCount < template.totalCount
    ),
  
  /** 获取筛选后的模板 */
  getFilteredTemplates: (state: IScheduleState): IScheduleTemplate[] => {
    let filtered = state.templates;
    const { filters, searchKeyword } = state.templateFilters;
    
    // 应用筛选条件
    if (filters.studentId) {
      filtered = filtered.filter(template => template.studentId === filters.studentId);
    }
    
    if (filters.studentIds && filters.studentIds.length > 0) {
      filtered = filtered.filter(template => filters.studentIds!.includes(template.studentId));
    }
    
    if (filters.courseId) {
      filtered = filtered.filter(template => template.courseId === filters.courseId);
    }
    
    if (filters.dayOfWeek) {
      filtered = filtered.filter(template => template.dayOfWeek === filters.dayOfWeek);
    }
    
    if (filters.status !== undefined) {
      filtered = filtered.filter(template => template.status === filters.status);
    }
    
    if (filters.hasRemainingCount !== undefined) {
      filtered = filtered.filter(template => {
        const hasRemaining = template.completedCount < template.totalCount;
        return filters.hasRemainingCount ? hasRemaining : !hasRemaining;
      });
    }
    
    // 应用搜索
    if (searchKeyword) {
      const keyword = searchKeyword.toLowerCase();
      filtered = filtered.filter(template => 
        template.location?.toLowerCase().includes(keyword) ||
        template.remark?.toLowerCase().includes(keyword)
      );
    }
    
    // 应用排序
    const { sortBy, sortOrder } = state.templateFilters;
    if (sortBy) {
      filtered.sort((a, b) => {
        let aValue: any = (a as any)[sortBy];
        let bValue: any = (b as any)[sortBy];
        
        if (typeof aValue === 'string') {
          aValue = aValue.toLowerCase();
          bValue = bValue.toLowerCase();
        }
        
        if (aValue < bValue) return sortOrder === 'asc' ? -1 : 1;
        if (aValue > bValue) return sortOrder === 'asc' ? 1 : -1;
        return 0;
      });
    }
    
    return filtered;
  },
  
  // 实例选择器
  /** 获取所有实例 */
  getAllInstances: (state: IScheduleState): IScheduleInstance[] => state.instances,
  
  /** 获取已安排的实例 */
  getScheduledInstances: (state: IScheduleState): IScheduleInstance[] => 
    state.instances.filter(instance => instance.status === ScheduleInstanceStatusEnum.SCHEDULED),
  
  /** 根据ID获取实例 */
  getInstanceById: (state: IScheduleState, id: string): IScheduleInstance | undefined => 
    state.instances.find(instance => instance.id === id),
  
  /** 根据模板ID获取实例 */
  getInstancesByTemplateId: (state: IScheduleState, templateId: string): IScheduleInstance[] => 
    state.instances.filter(instance => instance.templateId === templateId),
  
  /** 根据学生ID获取实例 */
  getInstancesByStudentId: (state: IScheduleState, studentId: string): IScheduleInstance[] => 
    state.instances.filter(instance => instance.studentId === studentId),
  
  /** 根据课程ID获取实例 */
  getInstancesByCourseId: (state: IScheduleState, courseId: string): IScheduleInstance[] => 
    state.instances.filter(instance => instance.courseId === courseId),
  
  /** 根据日期获取实例 */
  getInstancesByDate: (state: IScheduleState, date: string): IScheduleInstance[] => 
    state.instances.filter(instance => instance.date === date),
  
  /** 根据日期范围获取实例 */
  getInstancesByDateRange: (state: IScheduleState, startDate: string, endDate: string): IScheduleInstance[] => 
    state.instances.filter(instance => instance.date >= startDate && instance.date <= endDate),
  
  /** 获取补课实例 */
  getMakeupInstances: (state: IScheduleState): IScheduleInstance[] => 
    state.instances.filter(instance => instance.status === ScheduleInstanceStatusEnum.MAKEUP),
  
  /** 获取筛选后的实例 */
  getFilteredInstances: (state: IScheduleState): IScheduleInstance[] => {
    let filtered = state.instances;
    const { filters, searchKeyword } = state.instanceFilters;
    
    // 应用筛选条件
    if (filters.studentId) {
      filtered = filtered.filter(instance => instance.studentId === filters.studentId);
    }
    
    if (filters.studentIds && filters.studentIds.length > 0) {
      filtered = filtered.filter(instance => filters.studentIds!.includes(instance.studentId));
    }
    
    if (filters.courseId) {
      filtered = filtered.filter(instance => instance.courseId === filters.courseId);
    }
    
    if (filters.dateFrom) {
      filtered = filtered.filter(instance => instance.date >= filters.dateFrom!);
    }
    
    if (filters.dateTo) {
      filtered = filtered.filter(instance => instance.date <= filters.dateTo!);
    }
    
    if (filters.status !== undefined) {
      filtered = filtered.filter(instance => instance.status === filters.status);
    }
    
    if (filters.isMakeup !== undefined) {
      filtered = filtered.filter(instance => {
        const isMakeup = instance.status === ScheduleInstanceStatusEnum.MAKEUP;
        return filters.isMakeup ? isMakeup : !isMakeup;
      });
    }
    
    // 应用搜索
    if (searchKeyword) {
      const keyword = searchKeyword.toLowerCase();
      filtered = filtered.filter(instance => 
        instance.location?.toLowerCase().includes(keyword) ||
        instance.remark?.toLowerCase().includes(keyword)
      );
    }
    
    // 应用排序
    const { sortBy, sortOrder } = state.instanceFilters;
    if (sortBy) {
      filtered.sort((a, b) => {
        let aValue: any = (a as any)[sortBy];
        let bValue: any = (b as any)[sortBy];
        
        if (typeof aValue === 'string') {
          aValue = aValue.toLowerCase();
          bValue = bValue.toLowerCase();
        }
        
        if (aValue < bValue) return sortOrder === 'asc' ? -1 : 1;
        if (aValue > bValue) return sortOrder === 'asc' ? 1 : -1;
        return 0;
      });
    }
    
    return filtered;
  },
  
  // 混合视图选择器
  /** 获取选中学生的实例 */
  getSelectedStudentsInstances: (state: IScheduleState): IScheduleInstance[] => {
    if (state.selectedStudentIds.length === 0) {
      return state.instances;
    }
    return state.instances.filter(instance => 
      state.selectedStudentIds.includes(instance.studentId)
    );
  },
  
  /** 获取选中日期的实例 */
  getSelectedDateInstances: (state: IScheduleState): IScheduleInstance[] => 
    state.instances.filter(instance => instance.date === state.selectedDate),
  
  /** 获取选中学生在选中日期的实例 */
  getSelectedStudentsDateInstances: (state: IScheduleState): IScheduleInstance[] => {
    let filtered = state.instances.filter(instance => instance.date === state.selectedDate);
    
    if (state.selectedStudentIds.length > 0) {
      filtered = filtered.filter(instance => 
        state.selectedStudentIds.includes(instance.studentId)
      );
    }
    
    return filtered.sort((a, b) => a.startTime.localeCompare(b.startTime));
  },
  
  // 统计选择器
  /** 获取模板统计信息 */
  getTemplateStats: (state: IScheduleState) => {
    const templates = state.templates;
    return {
      total: templates.length,
      active: templates.filter(t => t.status === ScheduleTemplateStatusEnum.ACTIVE).length,
      completed: templates.filter(t => t.status === ScheduleTemplateStatusEnum.COMPLETED).length,
      suspended: templates.filter(t => t.status === ScheduleTemplateStatusEnum.SUSPENDED).length,
      cancelled: templates.filter(t => t.status === ScheduleTemplateStatusEnum.CANCELLED).length,
      withRemainingCount: templates.filter(t => t.completedCount < t.totalCount).length
    };
  },
  
  /** 获取实例统计信息 */
  getInstanceStats: (state: IScheduleState) => {
    const instances = state.instances;
    return {
      total: instances.length,
      scheduled: instances.filter(i => i.status === ScheduleInstanceStatusEnum.SCHEDULED).length,
      completed: instances.filter(i => i.status === ScheduleInstanceStatusEnum.COMPLETED).length,
      cancelled: instances.filter(i => i.status === ScheduleInstanceStatusEnum.CANCELLED).length,
      makeup: instances.filter(i => i.status === ScheduleInstanceStatusEnum.MAKEUP).length
    };
  },
  
  /** 获取学生课程统计 */
  getStudentStats: (state: IScheduleState, studentId: string) => {
    const templates = state.templates.filter(t => t.studentId === studentId);
    const instances = state.instances.filter(i => i.studentId === studentId);
    
    return {
      totalTemplates: templates.length,
      activeTemplates: templates.filter(t => t.status === ScheduleTemplateStatusEnum.ACTIVE).length,
      totalInstances: instances.length,
      completedInstances: instances.filter(i => i.status === ScheduleInstanceStatusEnum.COMPLETED).length,
      scheduledInstances: instances.filter(i => i.status === ScheduleInstanceStatusEnum.SCHEDULED).length,
      makeupInstances: instances.filter(i => i.status === ScheduleInstanceStatusEnum.MAKEUP).length
    };
  },
  
  // 状态选择器
  /** 检查模板是否正在加载 */
  isTemplateLoading: (state: IScheduleState): boolean => state.templateAsync.loading,
  
  /** 检查实例是否正在加载 */
  isInstanceLoading: (state: IScheduleState): boolean => state.instanceAsync.loading,
  
  /** 检查冲突检测是否正在加载 */
  isConflictLoading: (state: IScheduleState): boolean => state.conflictAsync.loading,
  
  /** 获取模板错误信息 */
  getTemplateError: (state: IScheduleState): string | null => state.templateAsync.error,
  
  /** 获取实例错误信息 */
  getInstanceError: (state: IScheduleState): string | null => state.instanceAsync.error,
  
  /** 获取冲突检测错误信息 */
  getConflictError: (state: IScheduleState): string | null => state.conflictAsync.error,
  
  /** 获取冲突信息 */
  getConflicts: (state: IScheduleState): IScheduleConflict[] => state.conflicts,
  
  /** 检查是否有冲突 */
  hasConflicts: (state: IScheduleState): boolean => state.conflicts.length > 0,
  
  // 选择状态选择器
  /** 获取选中的模板 */
  getSelectedTemplate: (state: IScheduleState): IScheduleTemplate | null => state.selectedTemplate,
  
  /** 获取选中的实例 */
  getSelectedInstance: (state: IScheduleState): IScheduleInstance | null => state.selectedInstance,
  
  /** 获取选中的模板ID列表 */
  getSelectedTemplateIds: (state: IScheduleState): string[] => state.selectedTemplateIds,
  
  /** 获取选中的实例ID列表 */
  getSelectedInstanceIds: (state: IScheduleState): string[] => state.selectedInstanceIds,
  
  /** 检查模板是否被选中 */
  isTemplateSelected: (state: IScheduleState, templateId: string): boolean => 
    state.selectedTemplateIds.includes(templateId),
  
  /** 检查实例是否被选中 */
  isInstanceSelected: (state: IScheduleState, instanceId: string): boolean => 
    state.selectedInstanceIds.includes(instanceId),
  
  /** 检查学生是否被选中 */
  isStudentSelected: (state: IScheduleState, studentId: string): boolean => 
    state.selectedStudentIds.includes(studentId),
  
  // UI状态选择器
  /** 获取当前视图类型 */
  getViewType: (state: IScheduleState) => state.viewType,
  
  /** 获取选中的日期 */
  getSelectedDate: (state: IScheduleState): string => state.selectedDate,
  
  /** 获取选中的学生ID列表 */
  getSelectedStudentIds: (state: IScheduleState): string[] => state.selectedStudentIds,
  
  /** 检查是否显示冲突检测 */
  isShowConflictDetection: (state: IScheduleState): boolean => state.showConflictDetection,
  
  /** 检查是否显示模板表单 */
  isShowTemplateForm: (state: IScheduleState): boolean => state.showTemplateForm,
  
  /** 获取模板表单模式 */
  getTemplateFormMode: (state: IScheduleState) => state.templateFormMode,
  
  /** 检查是否显示实例详情 */
  isShowInstanceDetail: (state: IScheduleState): boolean => state.showInstanceDetail,
  
  /** 检查是否显示批量操作面板 */
  isShowBatchPanel: (state: IScheduleState): boolean => state.showBatchPanel,
  
  /** 检查是否显示冲突对话框 */
  isShowConflictDialog: (state: IScheduleState): boolean => state.showConflictDialog
};

/**
 * 课表数据计算工具
 * @description 提供复杂的数据计算和分析功能
 */
export const scheduleCalculators = {
  /**
   * 计算模板的进度百分比
   * @param template 课程模板
   * @returns 进度百分比（0-100）
   */
  calculateTemplateProgress: (template: IScheduleTemplate): number => {
    if (template.totalCount === 0) return 0;
    return Math.round((template.completedCount / template.totalCount) * 100);
  },
  
  /**
   * 计算模板的剩余次数
   * @param template 课程模板
   * @returns 剩余次数
   */
  calculateRemainingCount: (template: IScheduleTemplate): number => {
    return Math.max(0, template.totalCount - template.completedCount);
  },
  
  /**
   * 计算两个时间段是否重叠
   * @param time1 时间段1
   * @param time2 时间段2
   * @returns 是否重叠
   */
  isTimeOverlap: (
    time1: { startTime: string; endTime: string },
    time2: { startTime: string; endTime: string }
  ): boolean => {
    return time1.startTime < time2.endTime && time1.endTime > time2.startTime;
  },
  
  /**
   * 获取指定日期范围内的所有日期
   * @param startDate 开始日期
   * @param endDate 结束日期
   * @returns 日期数组
   */
  getDateRange: (startDate: string, endDate: string): string[] => {
    const dates: string[] = [];
    const start = new Date(startDate);
    const end = new Date(endDate);
    
    for (let date = new Date(start); date <= end; date.setDate(date.getDate() + 1)) {
      dates.push(date.toISOString().split('T')[0]);
    }
    
    return dates;
  },
  
  /**
   * 获取指定日期是星期几
   * @param date 日期字符串
   * @returns 星期枚举值
   */
  getDayOfWeek: (date: string): DayOfWeekEnum => {
    const dayOfWeek = new Date(date).getDay();
    return dayOfWeek === 0 ? DayOfWeekEnum.SUNDAY : dayOfWeek as DayOfWeekEnum;
  },
  
  /**
   * 获取本周的开始日期（星期一）
   * @param date 参考日期
   * @returns 本周开始日期
   */
  getWeekStartDate: (date: string): string => {
    const d = new Date(date);
    const day = d.getDay();
    const diff = d.getDate() - day + (day === 0 ? -6 : 1); // 调整为星期一
    const monday = new Date(d.setDate(diff));
    return monday.toISOString().split('T')[0];
  },
  
  /**
   * 获取本周的所有日期
   * @param weekStartDate 本周开始日期
   * @returns 本周日期数组
   */
  getWeekDates: (weekStartDate: string): string[] => {
    const dates: string[] = [];
    const start = new Date(weekStartDate);
    
    for (let i = 0; i < 7; i++) {
      const date = new Date(start);
      date.setDate(start.getDate() + i);
      dates.push(date.toISOString().split('T')[0]);
    }
    
    return dates;
  }
};